package com.basic.library.binding.viewadapter.textview;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Spanned;
import android.text.style.ClickableSpan;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.databinding.BindingAdapter;

import com.basic.library.utils.TextViewUtils;

public final class ViewAdapter {

    /**
     * 会覆盖原生的属性(android:drawableStart="@{viewModel.drawable_right}")
     * 若要不覆盖用android:drawableEnd="@{@drawable/eye}"，套了一层@{}；
     * 当两者是冲突的 会覆盖 ， 只能用一种
     *
     * @param view
     * @param left
     * @param top
     * @param right
     * @param bottom
     */
    @BindingAdapter(value = {"android:drawableStart", "android:drawableTop", "android:drawableEnd", "android:drawableBottom", "android:drawableTint"}, requireAll = false)
    public static void setCompoundDrawable(TextView view, final int left, final int top, final int right, final int bottom, final int tint) {
        if (tint == 0)
            view.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);
        else {
            Context context = view.getContext();
            view.setCompoundDrawables(tintDrawable(context, left, tint),
                    tintDrawable(context, top, tint),
                    tintDrawable(context, right, tint),
                    tintDrawable(context, bottom, tint));
        }
    }

    public static Drawable tintDrawable(Context context, int drawable, int colorId) {
        if (drawable == 0) return null;
        Drawable wrappedDrawable = DrawableCompat.wrap(ContextCompat.getDrawable(context, drawable));
        wrappedDrawable.setBounds(0, 0, wrappedDrawable.getMinimumWidth(), wrappedDrawable.getMinimumHeight());
        DrawableCompat.setTint(wrappedDrawable, ContextCompat.getColor(context, colorId));
        return wrappedDrawable;
    }

    public static Drawable tintDrawable(Context context, @NonNull Drawable drawable, int colorId) {
        Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
        DrawableCompat.setTint(wrappedDrawable, ContextCompat.getColor(context, colorId));
        return wrappedDrawable;
    }

    @BindingAdapter(value = {"spanned", "clickableSpan"}, requireAll = true)
    public static void setMyClickableSpan(TextView view, Spanned spanned, ClickableSpan clickableSpan) {
        if (clickableSpan != null)
            TextViewUtils.INSTANCE.setMyClickableSpan(view, spanned, clickableSpan);
    }
}

